/*
 * @lc app=leetcode.cn id=203 lang=typescript
 *
 * [203] 移除链表元素
 */

// @lc code=start
/**
 * Definition for singly-linked list.
 * class ListNode {
 *     val: number
 *     next: ListNode | null
 *     constructor(val?: number, next?: ListNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.next = (next===undefined ? null : next)
 *     }
 * }
 */

function removeElements(head: ListNode | null, val: number): ListNode | null {
  if (head === null) return head;
  const dummy = new ListNode(0, head);
  let p1 = dummy;
  let p2 = head;
  while (p2) {
    if (p2.val !== val) {
      p1.next = p2;
      p1 = p1.next;
    }
    p2 = p2.next;
  }

  // 遍历结束，将p1的下一个指针指向null
  p1.next = null;

  return dummy.next;
}
// @lc code=end
